import React, { Component } from 'react'
import { Modal, Button, Row, Col, Popconfirm, Tooltip, Radio } from 'antd';
const RadioGroup = Radio.Group;
import ParamsInput from "@common/presentational/ParamsInput";
import _ from 'lodash'
import notify from "@utils/tip";
class MapRangeSelector extends Component {
    constructor(props) {
        super(props)
        const { longitude, latitude, deliver_regions } = this.props || {};
        this.state = {
            visible: false,
            edit: false,
            latitude,
            longitude,
            deliver_regions,
            idx: '',
            shipping_fee: '',
            starting_fee: '',
            Key: 1,
            r: 1,
        }
        this.map = null
        this.marker = null
        this.polyEditor = null
        this.polygon = null
        this.searchService = null
    }

    componentWillReceiveProps(nextProps) {
        if ('deliver_regions' in nextProps) {
            if (this.state.deliver_regions !== nextProps.deliver_regions || this.state.latitude !== nextProps.latitude || this.state.longitude !== nextProps.longitude) {
                this.setState({
                    deliver_regions: nextProps.deliver_regions,
                    latitude: nextProps.latitude,
                    longitude: nextProps.longitude,
                });
            }
        }
    }

    getPointFromCenterPointAndRadius = (centerPoint, radius) => {
        let arr = new Array()
        let r = 6371000.79;
        let numPoints = 40;
        let phase = 2 * Math.PI / numPoints;
        for (let i = 0; i < numPoints; i++) {
            let dx = (radius * Math.cos(i * phase));
            let dy = (radius * Math.sin(i * phase));

            let dLng = dx / (r * Math.cos(centerPoint[1] * Math.PI / 180) * Math.PI / 180);
            let dLat = dy / (r * Math.PI / 180);
            let newLng = centerPoint[0] + dLng;
            let newLat = centerPoint[1] + dLat;
            arr[i] = [Number(newLng.toFixed(6)), Number(newLat.toFixed(6))]
        }
        return arr
    }

    initMap = (value) => {
        const { longitude, latitude, deliver_regions, edit, idx } = this.state
        const _deliver_regions = _.cloneDeep(deliver_regions)
        //获取城市列表接口设置中心点
        this.map = new AMap.Map('mapRangeSelector', {
            resizeEnable: true,
            zoom: 15,
            defaultCursor: 'pointer',
            showIndoorMap: false,
        })

        this.marker = new AMap.Marker({
            position: [longitude, latitude],
        });
        this.map.add(this.marker)
        let path = ''
        if (edit) {
            path = _deliver_regions[idx].coordinates
        } else {
            let r = value * 1000
            let o = [longitude, latitude]//圆心
            path = this.getPointFromCenterPointAndRadius(o, r)
        }

        //  【lng ， lat】

        this.polygon = new AMap.Polygon({
            path: path,
            strokeColor: "#FF33FF",
            strokeWeight: 6,
            strokeOpacity: 0.2,
            fillOpacity: 0.4,
            fillColor: '#1791fc',
            zIndex: 50,
        })

        this.map.add(this.polygon)
        this.map.addControl(new AMap.ToolBar())
        this.map.addControl(new AMap.Scale())
        // 缩放地图到合适的视野级别
        this.map.setFitView([this.polygon])

        this.polyEditor = new AMap.PolyEditor(this.map, this.polygon)
        this.polyEditor.open()

        this.polyEditor.on('end', (event) => {
            this.submitModal(event.target.getPath())
        })

        this.searchService = new AMap.Geocoder({});
    }

    changeMap = (value) => {
        const { longitude, latitude, Key } = this.state
        this.setState({
            r: value
        })
        let path = ''
        let r = value * 1000
        let o = [longitude, latitude]//圆心
        path = this.getPointFromCenterPointAndRadius(o, r)

        //  【lng ， lat】
        this.map.clearMap()

        this.marker = new AMap.Marker({
            position: [longitude, latitude],
        });
        this.map.add(this.marker)

        if (Key == 1) {
            this.polygon = new AMap.Polygon({
                path: path,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                fillColor: '#1791fc',
                zIndex: 50,
            })

            this.map.add(this.polygon)

            this.map.setFitView([this.polygon])

            this.polyEditor = new AMap.PolyEditor(this.map, this.polygon)
            this.polyEditor.open()

            this.polyEditor.on('end', (event) => {
                this.submitModal(event.target.getPath())
            })
        } else {
            let mouseTool = new AMap.MouseTool(this.map)
            mouseTool.polygon({
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillColor: '#1791fc',
                fillOpacity: 0.4,
                // 线样式还支持 'dashed'
                strokeStyle: "solid",
                // strokeStyle是dashed时有效
                // strokeDasharray: [30,10],
            })
            mouseTool.on('draw', (event) => {
                let path = event.obj.getPath()
                if (path.length == 1) {
                    path = path[0]
                }
                let arr = new Array();
                for (let i = 0; i < path.length; i++) {
                    arr[i] = [path[i].lng, path[i].lat]
                }
                this.map.clearMap()
                this.polygon = new AMap.Polygon({
                    path: path,
                    strokeColor: "#FF33FF",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: '#1791fc',
                    zIndex: 50,
                })

                this.map.add(this.polygon)

                this.map.setFitView([this.polygon])

                this.polyEditor = new AMap.PolyEditor(this.map, this.polygon)
                this.polyEditor.open()

                this.polyEditor.on('end', (event) => {
                    this.submitModal(event.target.getPath())
                })
            })
        }
    }

    submitModal = (path) => {
        if (path.length == 1) {
            path = path[0]
        }
        let arr = new Array();
        let actions = []
        let cityCode = []
        for (let i = 0; i < path.length; i++) {
            arr[i] = [path[i].lng, path[i].lat]
            let action = () => {
                return new Promise(resolve => {
                    this.searchService.getAddress(arr[i], (status, addRes) => {
                        if (status === 'complete' && addRes.regeocode) {
                            let addressComponent = addRes.regeocode.addressComponent
                            cityCode.push(`156${addressComponent.adcode.slice(-6, -2)}00`)
                            resolve()
                        }
                    });
                })
            }
            actions.push(action())
        }
        Promise.all(actions).then(() => {
            let cityCodes = Array.from(new Set(cityCode))
            if (cityCodes.length > 1) {
                notify('范围不能超过当前城市', 'error')
                return false;
            }
            const { starting_fee, shipping_fee, edit, idx, deliver_regions } = this.state
            if (edit) {
                const _deliver_regions = _.cloneDeep(deliver_regions)
                _deliver_regions[idx].coordinates = [arr]
                _deliver_regions[idx].starting_fee = parseInt(starting_fee)
                _deliver_regions[idx].shipping_fee = parseInt(shipping_fee)
                _deliver_regions[idx].city_code = Number(cityCodes[0])
                this.setState({
                    deliver_regions: _deliver_regions,
                    visible: false
                }, () => {
                    this.props.onsubmit(_deliver_regions)
                })
            } else {
                const _deliver_regions = _.cloneDeep(deliver_regions)
                _deliver_regions.push({
                    'coordinates': [
                        arr
                    ],
                    'starting_fee': parseInt(starting_fee),
                    'shipping_fee': parseInt(shipping_fee),
                    'city_code': Number(cityCodes[0])
                })
                this.setState({
                    deliver_regions: _deliver_regions,
                    visible: false
                }, () => {
                    this.props.onsubmit(_deliver_regions)
                })
            }
        })
    }

    handleHide = (visible) => {
        this.setState({
            visible,
            idx: '',
            Key: 1
        })
    }

    handleOk = () => {
        const { shipping_fee, starting_fee, } = this.state
        if (shipping_fee === '' || typeof (shipping_fee) === 'undefined') {
            notify('请输入配送费', 'warn')
            return
        }
        if (starting_fee === '' || typeof (starting_fee) === 'undefined') {
            notify('请输入起送价', 'warn')
            return
        }
        this.polyEditor.close()
    }

    deleteRange = (idx) => {
        const { deliver_regions } = this.state
        const _deliver_regions = _.cloneDeep(deliver_regions)
        this.setState({
            deliver_regions: _deliver_regions.splice(idx, 1)
        }, () => {
            this.props.onsubmit(_deliver_regions)
        })
    }

    editRange = (idx) => {
        const { deliver_regions } = this.state
        this.setState({
            visible: true,
            edit: true,
            idx,
            shipping_fee: deliver_regions[idx].shipping_fee,
            starting_fee: deliver_regions[idx].starting_fee,
        }, () => {
            setTimeout(() => {
                this.initMap()
            })
        })
    }

    addRange = () => {
        const { deliver_regions } = this.state
        if (deliver_regions.length >= 10) {
            notify('最多添加十个区域', 'warn')
            return
        }
        this.setState({
            visible: true,
            edit: false,
            starting_fee: '',
            shipping_fee: '',
        }, () => {
            setTimeout(() => {
                this.initMap(1)
            })
        })
    }

    changeNumber(type, value) {
        if (type == 'ship') {
            this.setState({
                shipping_fee: value
            })
        } else if (type == 'start') {
            this.setState({
                starting_fee: value
            })
        }
    }

    handleKeyChange = (e) => {
        this.setState({
            Key: e.target.value,
        }, () => {
            this.changeMap(1)
        });
    }

    render() {
        const { deliver_regions, visible, edit, idx, starting_fee, shipping_fee, latitude, longitude, Key, r } = this.state
        const { canEdit, unFailure } = this.props
        const RangeDetail = (deliver_regions || []).map((mConfig, idx) => {
            const isPointInRing = AMap.GeometryUtil.isPointInRing([longitude, latitude], _.cloneDeep(mConfig.coordinates))
            return (
                <Row key={idx} className={`mgt-12 flex-row-between customer-table-line ${isPointInRing || unFailure ? '' : 'unuse-range'}`}>
                    <Col span="4" className="ft-16 ft-clr-d">
                        {`区域${idx + 1}`}
                    </Col>
                    <Col span="6" className="ft-14 ft-clr-ml">
                        {`起送价: ${mConfig.starting_fee}元`}
                    </Col>
                    <Col span="6" className="ft-14 ft-clr-ml">
                        {`配送费: ${mConfig.shipping_fee}元`}
                    </Col>
                    { canEdit ?
                        <Col span="7" className="txr">
                            {isPointInRing || unFailure ?
                                <span className='mgr-8 ft-hover' onClick={() => this.editRange(idx)}>编辑</span>
                                :
                                <Tooltip placement="top" title="店铺位置不在配送范围内">
                                    <span className="mgr-8 ft-hover">编辑</span>
                                </Tooltip>}
                            <Popconfirm title="确定要删除这个区域吗？"
                                onConfirm={() => this.deleteRange(idx)}
                                onCancel={() => { }}>
                                <span className='mgr-8 ft-hover'>删除</span>
                            </Popconfirm>
                        </Col> : null}
                    { isPointInRing || unFailure ? null :
                        <Col span='24'>
                            <span>此配送范围已失效</span>
                        </Col>}
                </Row>
            )
        })

        return (
            <div>
                { RangeDetail}
                { canEdit ?
                    <Button className="button-small mgt-8"
                        type="primary"
                        ghost
                        onClick={() => this.addRange()}
                    >＋添加区域</Button> : null}
                <Modal
                    title={'配送区域'}
                    className={"map-range-selector-container"}
                    visible={visible}
                    maskClosable={true}
                    onOk={this.handleOk}
                    destroyOnClose={true}
                    width={688}
                    height={768}
                    footer={null}
                    onCancel={() => this.handleHide(false)}
                >
                    <div className='map-range-modalbox'>
                        <Row className="mgt-16">
                            <Col span="4">
                                <span className='ft-clr-d'>起送价:</span>
                            </Col>
                            <Col span="20">
                                <ParamsInput
                                    className="mgl-16"
                                    style={{ width: '480px' }}
                                    value={starting_fee}
                                    onChange={this.changeNumber.bind(this, 'start')}
                                    placeholder="起送价"
                                /> 元
                            </Col>
                        </Row>
                        <Row className="mgt-16">
                            <Col span="4">
                                <span className='ft-clr-d'>配送费:</span>
                            </Col>
                            <Col span="20">
                                <ParamsInput
                                    className="mgl-16"
                                    style={{ width: '480px' }}
                                    value={shipping_fee}
                                    onChange={this.changeNumber.bind(this, 'ship')}
                                    placeholder="配送费"
                                /> 元
                            </Col>
                        </Row>
                        {!edit ? <Row className="mgt-16">
                            <Col span="4"><span className='ft-clr-d'>配送方式:</span></Col>
                            <Col span="20">
                                <RadioGroup className='mgl-16' onChange={this.handleKeyChange} value={Key}>
                                    <Radio value={0}>多边形区域</Radio>
                                    <Radio value={1}>圆形区域</Radio>
                                </RadioGroup>
                            </Col>
                        </Row> : null}
                        {!edit  && Key=='1' ?<Row className="mgt-16">
                            <Col span="4">
                                <span className='ft-clr-d'>半径:</span>
                            </Col>
                            <Col span="20">
                                <ParamsInput
                                    className="mgl-16"
                                    value={r}
                                    style={{ width: '480px' }}
                                    onChange={this.changeMap.bind(this)}
                                    placeholder="半径"
                                />公里
                            </Col>
                        </Row> : null}
                        <Row className="mgt-16">
                            <Col span="4">
                            </Col>
                            <Col span="20">
                                <div className="mgl-16 map-range-selector" id="mapRangeSelector"></div>
                            </Col>
                        </Row>
                        <div className="modal-button-line">
                            <Button className="mgr-16" onClick={() => this.handleHide(false)}>取消</Button>
                            <Button type="primary" onClick={this.handleOk}>保存</Button>
                        </div>
                    </div>
                </Modal>
            </div>
        )
    }
}

export default MapRangeSelector